var api = require('../../utils/api.js');
var app = getApp();
var WxParse = require('../../wxParse/wxParse.js');
import jiuaiDebounce from '../../utils/jiuai-debounce.js'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    // colorArr:['黄色','绿色','蓝色'],
    // sizeArr: ['110', '120', '130', '110', '120', '130', '110', '120', '130'],
    cid: 0,
    sid: 0,
    goodsNum: 0,
    urls: [],
    goods_id: '',
    dataList: '',
    catNum: 0,
    modalName: null,
    current: '',
    urlsArray: [],
    preview: false,
    noGoodsList:[]
    // wx_img:[]
  },

  onChange(event) {
    console.log(event.detail);
  },

  onClickIcon(e) {
    console.log(e.target.id, '点击图标');
    let clickId = e.target.id;

    //购物车
    if (clickId == 2) {
      wx.navigateTo({
        url: "/pages/shopCar/shopCar"
      })
    }
    //客服
    if (clickId == 1) {
      if (!this.data.current) {
        return wx.showToast({
          title: '暂无客服',
          icon: 'none'
        })
      }
      this.setData({
        modalName: e.currentTarget.dataset.target
      })
    }
  },


  //客服二维码预览
  preImage() {
    // console.log(this.data.urlsArray)
    wx.previewImage({
      current: this.data.current, // 当前显示图片的http链接
      urls: this.data.urlsArray // 需要预览的图片http链接列表
    })
  },
  changeColor() {
    let pattern = /\((\d*)\)$/g
    const {
      size
    } = this.data.dataList;
    let result
     const noGoodsList =size.map((item, index) => {
      result = pattern.exec(item)
      pattern.lastIndex = 0
      if (result[1] == 0) {
        return index
      }
      return null
    })
    // console.log(noGoodsList);
    this.setData({
      noGoodsList
    })
    
  },
  //跳转店铺列表
  toShopLink() {
    let store_id = this.data.dataList.store_id;
    wx.navigateTo({
      url: '/pages/shopList/shopList?store_id=' + store_id,
    })
  },

  toBuy(e) {
    if(this.data.dataList.inventory[this.data.sid]===0) {
      wx.showToast({
        title: '库存不足',
        icon: 'none',
      });
      return 
    }
    if(this.data.goodsNum===0){
      wx.showToast({
        title: '商品数不能为0',
        icon: 'none',
      });
      return 
    }
    let dataList = this.data.dataList;
    let format;
    let {
      color,
      size,
      store_id
    } = dataList;
    format = color[this.data.cid] + ',' + size[this.data.sid]
    let selectList = [{
      goods_id: this.data.goods_id,
      goods_num: this.data.goodsNum,
      format,
      store_id
    }]
    wx.navigateTo({
      url: '/pages/FillOrder/FillOrder?selectList=' + JSON.stringify(selectList) + '&type=0',
    })
  },

  //颜色选择
  selectColor(e) {
    var cid = e.currentTarget.dataset.cid;

    this.setData({
      cid,
      goodsNum: 1
      // sid: 0,
    })

  },
  //规格选择
  selectSize(e) {
    var sid = e.currentTarget.dataset.sid;
    // let {
    //   size
    // } = this.data.dataList
    // let pattern = /\((\d*)\)$/g
    // let stock_num = pattern.exec(size[sid])
    // if (Number(stock_num[1]) === 0) 
    this.setData({
      sid,
      goodsNum: 0
    })
  },
  
  //加入购物车
  toShopCar() {
    wx.navigateTo({
      url: '/pages/shopCar/shopCar',
    })
  },

  //购物车加
  addNum() {
    var goodsNum = this.data.goodsNum;
    goodsNum++
    if (goodsNum > this.data.dataList.inventory[this.data.sid]) {
      goodsNum = this.data.dataList.inventory[this.data.sid];
      wx.showToast({
        title: '不能购买更多',
        icon: 'none'
      })
    }
    this.setData({
      goodsNum
    })
  },

  //购物车减
  reduceNum() {
    var goodsNum = this.data.goodsNum;
    goodsNum--
    if (goodsNum < 0) {
      goodsNum = 0;
      wx.showToast({
        title: '最少添加一个',
        icon: 'none'
      })
    }
    this.setData({
      goodsNum
    })
  },

  //商品图片预览
  previewImages(e) {
    console.log(e)
    var type = e.currentTarget.dataset.type
    var current = e.currentTarget.dataset.url;
    if (type == 0) {
      this.setData({
        previewVideo: true,
        current
      })
      return
    }
    wx.previewImage({
      current, // 当前显示图片的http链接
      urls: this.data.urls // 需要预览的图片http链接列表
    })
  },
  // 预览视频结束
  end() {
    this.pause()
  },
  // 预览视频暂停
  pause() {
    this.setData({
      previewVideo: false,
      preview: false,
    })
  },
  onClickHide() {
    this.pause()
  },
  noop() {
    this.pause()
  },
  //商品详情
  getGoodsDetail() {
    const that = this
    let params = {
      token: wx.getStorageSync('token'),
      id: that.data.goods_id
    }
    api.fetchApi('/Order/goods_detail', params).then(res => {
      // console.log(res);
      let dataList = res.list;
      let content = dataList.information;
      let current = res.wx_img.wx_img || '';
      WxParse.wxParse('article', 'html', content, that, 25);
      let urls = []
      let url = []
      for (var index in dataList.banner) {
        urls = dataList.banner[index].url
        url = url.concat(urls)
      }
      if (dataList.banner[0].type == 0) {
        url.splice(0, 1)
      }
      that.setData({
        dataList,
        urls: url,
        catNum: res.cart_num,
        // wx_img,
        current,
        urlsArray: [current]
      })
      // that.changeColor()
      that.getShopInfo();
    })
  },
  previewVideo() {
    const that = this
    that.setData({
      preview: true,
    })
  },

  //加入购物车
  addShopCar() {
    if(this.data.dataList.inventory[this.data.sid]===0) {
      wx.showToast({
        title: '库存不足',
        icon: 'none',
      });
      return 
    }
    if(this.data.goodsNum===0){
      wx.showToast({
        title: '商品数不能为0',
        icon: 'none',
      });
      return 
    }
    jiuaiDebounce.canDoFunction({
      key: "tap", //基于此值判断是否可以操作，如两个方法传入了同样的key，则会混淆，建议传入调用此事件的方法名，简单好梳理
      time: 3000, //如果传入time字段，则为定时器后，自动解除锁定状态，单位（毫秒）
      success: () => { //成功中调用应该操作的方法，被锁定状态不会执行此代码块内的方法
        wx.showLoading({
          mask: true
        })
        let dataList = this.data.dataList;
        let format;
        let {
          color,
          size
        } = dataList;
        format = color[this.data.cid] + ',' + size[this.data.sid]

        let params = {
          token: wx.getStorageSync('token'),
          goods_id: this.data.goods_id,
          goods_num: this.data.goodsNum,
          format
        }
        api.fetchApi('/Cart/add', params).then(res => {
          wx.hideLoading();
          wx.showToast({
            title: '添加购物车成功'
          })
          setTimeout(() => {
            this.getGoodsDetail()
          }, 1000)
        })
      }
    })


  },

  // 查询店铺信息
  getShopInfo() {
    api.fetchApi('goods/store_info', {
      token: wx.getStorageSync('token'),
      store_id: this.data.dataList.store_id
    }).then(res => {

      var shopInfo = res.data;
      this.setData({
        shopInfo,
      })
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var goods_id = options.id
    this.setData({
      goods_id
    })
    this.getGoodsDetail();

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})